package com.dys.flink.wc1.netty;

import com.dys.flink.wc1.model.Product;
import com.dys.flink.wc1.netty.handler.ProductClientHandler;
import com.dys.flink.wc1.netty.handler.ProductDecoder;
import com.dys.flink.wc1.netty.handler.ProductEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldPrepender;

import java.util.Random;
import java.util.Scanner;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ProductClient {
    private final String host;
    private final int port;
    
    public ProductClient(String host, int port) {
        this.host = host;
        this.port = port;
    }
    
    public void run() throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
             .channel(NioSocketChannel.class)
             .handler(new ChannelInitializer<SocketChannel>() {
                 @Override
                 protected void initChannel(SocketChannel ch) throws Exception {
                     ChannelPipeline pipeline = ch.pipeline();
                     // 出站：先自动加 4 字节长度前缀
                     pipeline.addLast(new LengthFieldPrepender(4));
                    // 再编码
                     pipeline.addLast(new ProductEncoder());
                    // 入站：先拆帧
                     pipeline.addLast(new ProductDecoder());
                     pipeline.addLast(new ProductClientHandler());
                 }
             });
            
            ChannelFuture f = b.connect(host, port).sync();
            Channel channel = f.channel();
            
            System.out.println("Connected to server " + host + ":" + port);
            System.out.println("Choose mode:");
            System.out.println("1. Manual input");
            System.out.println("2. Auto generate");
            System.out.print("Enter choice (1 or 2): ");
            
            Scanner scanner = new Scanner(System.in);
            int choice = scanner.nextInt();
            scanner.nextLine(); // consume newline
            
            if (choice == 1) {
                manualInput(channel, scanner);
            } else {
                autoGenerate(channel);
            }
            
            channel.closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }
    
    private void manualInput(Channel channel, Scanner scanner) {
        System.out.println("Manual input mode - Enter product data (format: id,name,price) or 'quit' to exit:");
        
        while (true) {
            System.out.print("> ");
            String line = scanner.nextLine().trim();
            
            if ("quit".equalsIgnoreCase(line)) {
                break;
            }
            
            try {
                String[] parts = line.split(",");
                if (parts.length == 3) {
                    String id = parts[0].trim();
                    String name = parts[1].trim();
                    double price = Double.parseDouble(parts[2].trim());
                    
                    Product product = new Product(id, name, price);
                    channel.writeAndFlush(product);
                    System.out.println("Sent: " + product);
                } else {
                    System.out.println("Invalid format. Use: id,name,price");
                }
            } catch (Exception e) {
                System.out.println("Error: " + e.getMessage());
            }
        }
    }
    
    private void autoGenerate(Channel channel) {
        System.out.println("Auto generate mode - Press Enter to stop...");
        
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
        Random random = new Random();
        String[] productNames = {"Laptop", "Phone", "Tablet", "Monitor", "Keyboard", "Mouse", "Headphones", "Camera"};
        
        Runnable generateTask = new Runnable() {
            private int counter = 1;
            
            @Override
            public void run() {
                String id = "P" + String.format("%04d", counter++);
                String name = productNames[random.nextInt(productNames.length)];
                double price = 100 + random.nextDouble() * 1900; // $100 - $2000
                
                Product product = new Product(id, name, price);
                channel.writeAndFlush(product);
                System.out.println("Auto-generated: " + product);
            }
        };
        
        // 每秒生成一个商品
        scheduler.scheduleAtFixedRate(generateTask, 0, 1, TimeUnit.SECONDS);
        
        // 等待用户输入停止
        try {
            System.in.read();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        scheduler.shutdown();
        System.out.println("Auto generation stopped.");
    }

    public static void main(String[] args) throws Exception {
        // 连接到客户端端口，不是 Flink 端口
        String host = "localhost";
        int port = 8888;  // 修改为客户端端口

        new ProductClient(host, port).run();
    }
}